package id.co.shuba.spamobile;

import java.util.Date;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import id.co.shuba.spamobile.model.UserInfo;

public class Sessions {
	public static final String KEY = "LOGIN_INFO";
	
	public static UserInfo getUser(Context ctx) {
		SharedPreferences settings = ctx.getSharedPreferences("LOGIN_INFO", Context.MODE_PRIVATE);
		String nip = settings.getString("nip", null); 
		if (nip == null)
			return null;
		
		UserInfo info = new UserInfo();
		info.setId(settings.getLong("id", 0));
		info.setNip(nip);
		info.setUserName(settings.getString("userName", null));
		info.setAoCode(settings.getString("aoCode", null));
		info.setUnitCode(settings.getString("unitCode", null));
		info.setPassword(settings.getString("password", null));
		info.setToken(settings.getString("token", null));
		info.setEncryptionKey(settings.getString("encryptionKey", null));
		info.setEmailAddress(settings.getString("emailAddress", null));
		info.setLastLogin(new Date(settings.getLong("lastLogin", Long.MIN_VALUE)));
		info.setLastOnline(new Date(settings.getLong("lastOnline", Long.MIN_VALUE)));
		info.setEmailAddress(settings.getString("imei", null));
		info.setSourceCode(settings.getString("sourceCode", null));	
		info.setTimeOut(settings.getInt("timeOut", 60));	
		info.setAoType(settings.getString("aoType", null));
		return info;
	}
	
	public static void reset(Context ctx) {
		SharedPreferences settings = ctx.getSharedPreferences("LOGIN_INFO", Context.MODE_PRIVATE);
		Editor edit = settings.edit();
		edit.clear();
		edit.commit();
	}
	
	public static void setUser(Context ctx, UserInfo info) {
		SharedPreferences settings = ctx.getSharedPreferences("LOGIN_INFO", Context.MODE_PRIVATE);		
		Editor edit = settings.edit();
		edit.putLong("id", info.getId());		
		edit.putString("nip", info.getNip());
		edit.putString("aoCode", info.getAoCode());
		edit.putString("unitCode", info.getUnitCode());
		edit.putString("userName", info.getUserName());
		edit.putString("encryptionKey", info.getEncryptionKey());
		edit.putString("emailAddress", info.getEmailAddress());
		edit.putString("imei", info.getImei());
		edit.putString("token", info.getToken());
		edit.putLong("lastOnline", info.getLastOnline().getTime());
		edit.putLong("lastLogin", info.getLastLogin().getTime());
		edit.putString("password", info.getPassword());
		edit.putString("sourceCode", info.getSourceCode());
		edit.putInt("timeOut", info.getTimeOut());
		edit.putString("aoType", info.getAoType());
		edit.commit();		
	}
}
